package com.cat.chapter050;

/**
 * @author cat
 * @description https://leetcode.cn/problems/trapping-rain-water/
 * @create 2025/7/21 10:04
 * @since JDK17
 */

public class Solution02 {
    public int trap(int[] height) {
        int n = height.length, lmax = height[0], rmax = height[n - 1], ans = 0;
        for (int l = 0, r = n - 1; l <= r; ) {
            if (lmax <= rmax) {
                ans += Math.max(0, lmax - height[l]);
                lmax = Math.max(lmax, height[l++]);
            } else {
                ans += Math.max(0, rmax - height[r]);
                rmax = Math.max(rmax, height[r--]);
            }
        }
        return ans;
    }
}
